import json
import re
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
import requests
from django.shortcuts import render, redirect
from django.urls import reverse



def debug_config(request):
    '''
    测试配置
    :param request:
    :param config_id:
    :return:
    '''
    print(122)
    bb = 'debug'
    change = 1
    api_debug_url = reverse('task:api_debug_config')
    api_debug_result_url = reverse('task:api_debug_result')
    api_debug_kill_url = reverse('task:api_debug_kill')
    code = ''
    return render(request, 'config/debug.html', locals())

def api_debug_config(request):
    try:
        if request.method == 'POST':
            tag = request.POST.get('tag')
            bb = request.POST.get('bb', '')
            type_p = request.POST.get('type', '')
            if bb == 'debug1':
                debug_host = 'http://192.168.18.21:8887'
            else:
                debug_host = 'http://192.168.18.23:8887'
            if type_p == '0' or type_p == '2':
                debug_host = 'http://192.168.18.23:8887'
            result = ''
            if request.POST.get("code"):
                redis_using = re.search(r'redis.', request.POST.get('code'), re.IGNORECASE)
                # 如果找到了 "mysql"，则返回 True，否则返回 False
                redis_using = bool(redis_using)
                match = re.search(r'mysql.', request.POST.get('code'), re.IGNORECASE)

                # 如果找到了 "mysql"，则返回 True，否则返回 False
                mysql_using = bool(match)
                if redis_using or mysql_using:
                    return HttpResponse("测试机禁止链接redis和mysql")
            if tag == 'check_service':
                url = debug_host + '/webspider/alive'
                try:
                    res = requests.get(url, timeout=30)
                    result = 1
                except Exception:
                    result = 0

            elif tag == 'getstatus':
                url = debug_host + '/webspider/status'
                params = {'code': request.POST.get('code')}
                try:
                    result = requests.get(url, timeout=30, params=params)
                    result = result.text
                except Exception:
                    result = '服务异常'
            elif tag == 'runcode':
                type_p = request.POST.get('type')
                proxy_p = request.POST.get('proxy')
                code_p = request.POST.get('code')
                data_post = {'type': type_p, 'proxy': proxy_p, 'code': code_p}
                if type_p == '2':
                    func_name = request.POST.get('func_name')
                    url_debug = request.POST.get('url_debug')
                    data_post.update({'func_name': func_name, 'url': url_debug})
                try:
                    url = debug_host + '/webspider/run_code'
                    result = requests.post(url, timeout=30, data=data_post)
                    result = result.text
                    result = re.sub('(?i)from redis import \S+?', "", result)
                    result = re.sub('(?i)import redis', "", result)
                except Exception:
                    result = ''
            return HttpResponse(result)
    except Exception:
        result = ''
        return HttpResponse(result)


# @api_view(['GET', 'POST'])
def api_debug_result(request):
    if request.method == 'POST':
        tag = request.POST.get('tag')
        bb = request.POST.get('bb', '')
        if bb == 'debug1':
            debug_host = 'http://192.168.18.21:8887'
        else:
            debug_host = 'http://192.168.18.23:8887'
        tag = request.POST.get('tag')
        uuid = request.POST.get('uuid')
        type_p = request.POST.get('type')
        if type_p == '0' or type_p == '2':
            debug_host = 'http://192.168.18.23:8887'
        # global debug_host
        params = dict()
        if tag == 'getresult':
            try:
                url = debug_host + '/webspider/code_result?code=' + uuid
                result = requests.get(url, timeout=30, params=params)
                result = result.text
            except Exception:
                result = json.dumps({'code': 'uuid', 'result': '服务异常'})
            result = json.loads(result)
            if result['result'] in ['', ]:
                result = {'code': result['code'], 'result': 'uuid', 'status': '返回结果为空，后台继续尝试请求！'}
                return JsonResponse(result)
            if type_p == '2':
                s = result['result']
                if s:
                    try:
                        s1 = json.loads(s)
                        # 利用content字段判断是否是正文
                        if len(s1['data']) > 0:
                            result['content'] = 1
                            real_content = list()
                            for i in s1['data']:
                                real_c = json.loads(i)
                                real_content.append(real_c)
                            json_content = real_content[0]
                            result['real_content'] = json.dumps(json_content)
                        else:
                            result['content'] = 0

                        for i in s1['urls']:
                            if isinstance(i['url'], str):
                                url_real = i['url']
                                i['post_data'] = json.dumps(i['url'])
                                i['url'] = url_real
                            else:
                                url_real = i['url']['url']
                                i['post_data'] = json.dumps(i['url'])
                                i['url'] = url_real
                        result['result'] = json.dumps(s1)
                    except Exception:
                        result['result'] = s
            return JsonResponse(result)


# @api_view(['GET', 'POST'])
def api_debug_kill(request):
    if request.method == 'POST':
        tag = request.POST.get('tag')
        bb = request.POST.get('bb', '')
        type_p = request.POST.get('type', '')
        if bb == 'debug1':
            debug_host = 'http://192.168.18.21:8887'
        else:
            debug_host = 'http://192.168.18.23:8887'
        if type_p == '0' or type_p == '2':
            debug_host = 'http://192.168.18.23:8887'
        url = debug_host + '/webspider/kill'
        code = request.POST.get('code')
        params = {'code': code}
        result = requests.get(url, timeout=3, params=params)
        return HttpResponse(result.status_code)
